#!/bin/bash

sday=$1
max=$2
WGETSUBPATH="/php/"
API_PREFIX="coacht_api"
UC_PREFIX="coacht_uc"
FTPUSER="ftplog"
FTPPWD="poc123"

BASEDIR=$(dirname $0)
LOG_PATH="${BASEDIR}/log/"
mkdir -p ${LOG_PATH}
IPS=(10.171.47.178 10.171.114.102 10.170.193.18 10.172.183.81)

function download(){
	local tmpday=$1
	local tmpprefix=$2
	local tmpip=$3
	local remotepath="${tmpip}${WGETSUBPATH}${tmpprefix}/${tmpday}"
	local localdir="${LOG_PATH}"
	local log="${localdir}tmp.log"
	local loggz="${localdir}tmp.log.gz"
	wget -q ftp://${remotepath}.log -P "${localdir}" --ftp-user="$FTPUSER" --ftp-password="$FTPPWD" -O ${log}
	local wres=$?
	if [ $wres -eq 8 ];then
		wget -q ftp://${remotepath}.log.gz -P "${localdir}" --ftp-user="$FTPUSER" --ftp-password="$FTPPWD" -O ${loggz}
                if [ $? -eq 0 ];then
                	gunzip -f ${loggz}
			if [ $? -ne 0 ];then
				echo "解压缩${remotepath}.log.gz失败"
			else
				cat ${log} >> "${LOG_PATH}${tmpday}"
				if [ $? -ne 0 ];then
					echo "${remotepath}.log 追加至 ${LOG_PATH}${tmpday} 失败!"
				fi
			fi
                else
                        echo "${remotepath}.log.gz文件下载失败"
                fi
	else
		if [ $wres -ne 0 ];then
			echo "${remotepath}.log文件下载error code $wres"
		else
			cat ${log} >> "${LOG_PATH}${tmpday}"
			if [ $? -ne 0 ];then
				echo "${remotepath}.log 追加至 ${LOG_PATH}${tmpday} 失败"
			fi
		fi
	fi
}

i=0
while true
do
	day=`date -d "$sday +$i day " +%Y-%m-%d`
	:>"${LOG_PATH}$day"
	((i++))
	for ip in ${IPS[*]}
	do
		download $day $API_PREFIX $ip
		download $day $UC_PREFIX $ip
	done
	if [ "$i" -ge "$max" ];then
		break
	fi
done
